const express = require('express')
const authenticateToken = require('../utils/authMiddleware.js') // 引入身份验证中间件
const xlsx = require('xlsx')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath } = require('../utils/constants.js') // 引入常量

const router = express.Router()
// 使用绝对路径
const filePath = getFilePath('users')

// 修改用户信息的路由 (需要身份验证)
router.post('/updateUserInfo', authenticateToken, (req, res) => {
  // 从 req.user 中获取用户账号
  const { account } = req.user
  const { newAccount, nickname, phone, gender, address, birthdate, avatar } = req.body

  const workbook = xlsx.readFile(filePath)
  const worksheet = workbook.Sheets['users']
  const usersData = xlsx.utils.sheet_to_json(worksheet)

  // 查找用户
  const userIndex = usersData.findIndex((user) => user.Account === account)

  if (userIndex === -1) {
    return sendResponse(res, 404, {}, '未找到该用户。')
  }

  // 检查新的账号是否已存在
  if (newAccount && usersData.some((user) => user.Account === newAccount && user.Account !== account)) {
    return sendResponse(res, 400, {}, '新账号已存在。')
  }

  // 更新用户信息，包括 Avatar 字段
  const updatedUser = {
    ...usersData[userIndex],
    Account: newAccount || usersData[userIndex].Account,
    Nickname: nickname || usersData[userIndex].Nickname,
    Phone: phone || usersData[userIndex].Phone,
    Gender: gender || usersData[userIndex].Gender,
    Address: address || usersData[userIndex].Address,
    Birthdate: birthdate || usersData[userIndex].Birthdate,
    Avatar: avatar || usersData[userIndex].Avatar
  }
  usersData[userIndex] = updatedUser

  // 将更新后的数据写回 Excel 文件
  const newSheet = xlsx.utils.json_to_sheet(usersData)
  workbook.Sheets['users'] = newSheet
  xlsx.writeFile(workbook, filePath)

  // 返回更新后的用户信息
  const { Password, ...updatedUserInfo } = updatedUser
  return sendResponse(res, 200, updatedUserInfo, '用户信息更新成功。')
})

module.exports = router
